# -*- coding: utf-8 -*-
'''
@Time    : 2021/5/5 14:27
@Author  : 小杰
@File    : OperationMysql.py
'''

import pymysql
# import pyMysql as db


# db = db.DataBase()
# sql = 'select * from students_0922'
# print(db.select_sql(sql))

import configparser


class OperationMysql(object):

    def __init__(self, db='db'):
        # ConfigParser模块在python中用来读取配置文件，
        # 配置文件的格式跟windows下的ini配置文件相似，
        # 可以包含一个或多个节(section), 每个节可以有多个参数（键 = 值）。
        # 使用的配置文件的好处就是不用在程序写死，可以使程序更灵活。
        # 注意：在python3中ConfigParser模块名已更名为configparser
        config = configparser.ConfigParser()
        # read(filename)  # 读取配置文件，直接读取ini文件内容
        config.read(r'K:\lebo17\python-automation-course-17\xiaojie\HomeWork18\.editorconfig')
        host = config.get(db, 'db_host')
        user = config.get(db, 'db_user')
        pwd = config.get(db, 'db_pass')
        name = config.get(db, 'db_name')
        port = eval(config.get(db, 'db_port'))
        # 打开数据库连接
        self.db = pymysql.connect(host=host, user=user, port=port, password=pwd, database=name)
        print("数据库开始")
        print(db)

    # 查询数据方法
    def db_select(self, sql):
        # 获得Cursor对象
        cur = self.db.cursor()
        # 执行select语句，并返回受影响的行数：查询一条数据
        count = cur.execute(sql)
        # 打印受影响的行数
        print("查询到%d条数据:" % count)
        for i in range(count):
            # 获取查询的结果
            result = cur.fetchone()
            # 打印查询的结果
            print(result)

    # 增删改
    def db_excute(self, sql, params=None):
        cursor = self.db.cursor()
        cursor.execute(sql, params)
        self.db.commit()
        print('操作数据库成功')

    def db_close(self):
        try:
            self.db.close()
            print("关闭数据库")
        except BaseException as e:
            print(e)


if __name__ == '__main__':
    operation = OperationMysql('db1')
    sql = 'select * from students_0922'
    operation.db_select(sql)
    print('-' * 100)
    operation = OperationMysql()
    sql = 'select * from students_0922'
    operation.db_select(sql)
    # sql1 = "drop table if EXISTS ceshi_kun;"
    # operation.db_excute(sql1)
    operation.db_close()
